<?php

namespace app\admin\controller;

class Levels extends Home
{
    protected static $levelsModel;

    public function __construct()
    {
        parent::__construct();
        self::$levelsModel = new \app\common\model\Levels();
    }

    /**
     * 会员级别列表
     * @return mixed
     */
    public function lists()
    {
        $list = self::$levelsModel->where('status', 1)->order('id asc')->select();
        if ($list) {
            foreach ($list as &$val) {
                $val['package_name'] = $val['package_id'] > 0 ? Db('packages')->where('id', $val['package_id'])->value('name') : '无';
                $val['contribution_release_rate'] *= 100;
                $val['active_tdb_rate'] *= 100;
            }
        }
        $this->assign('_list', $list);
        $this->assign('title', '会员级别列表');
        return $this->fetch();
    }

    /**
     * 获取会员级别
     * @return mixed
     */
    public function one()
    {
        $id = input('id');
        $rowInfo = [];
        if ($id > 0) {
            $rowInfo = self::$levelsModel->where('id', $id)->find();
            $rowInfo['contribution_release_rate'] *= 100;
            $rowInfo['active_tdb_rate'] *= 100;
        }

        $packages = Db('packages')->field('id,name')->where('status', 1)->select();

        $this->assign('row_info', $rowInfo);
        $this->assign('packages', $packages);
        $this->assign('title', '会员级别');
        return $this->fetch();
    }

    /**
     * 新增会员级别
     * @return mixed
     */
    public function addOredit()
    {
        $data = request()->post();
        $id = $data['id'];
        $data['contribution_release_rate'] *= 0.01;
        $data['active_tdb_rate'] *= 0.01;
        $data['update_time'] = time();
        if ($id) {
            unset($data['id']);
            $res = self::$levelsModel->where('id', $id)->update($data);
        } else {
            $data['create_time'] = time();
            $res = self::$levelsModel->insert($data);
        }

        if ($res) {
            $this->success('操作成功！', url('lists'));
        } else {
            $this->error('操作失败！');
        }
    }

    /**
     * 删除会员级别
     */
    public function del()
    {
        $ids = input('post.id');
        if (!is_array($ids)) {
            $ids = (array)$ids;
        }

        $res = self::$levelsModel->where('id', 'in', $ids)->delete();
        if ($res) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }
}